package com.lagou.ipersistence.mapping;

import com.lagou.ipersistence.session.Configuration;
import com.lagou.ipersistence.type.JdbcType;
import com.lagou.ipersistence.type.TypeHandler;
import com.lagou.ipersistence.type.TypeHandlerRegistry;
import lombok.Getter;
import sun.security.krb5.Config;

/**
 * 一个Mapper.xml中参数与JDBC参数的一个映射
 *
 * @author Yan Jiahong
 * Created 2020/11/8
 */
public class ParameterMapping {
    /**
     * 参数名, 从${xxx}, #{xxx}中解析出来的参数名
     */
    private String content;
    
    private Configuration configuration;
    
    private String property;
    
    private Class<?> javaType = Object.class;
    
    private JdbcType jdbcType;
    
    private String resultMapId;
    
    private TypeHandler<?> typeHandler;
    
    public ParameterMapping() {
    }
    
    public ParameterMapping(String content) {
        this.content = content;
    }
    
    public String getContent() {
        return content;
    }
    
    public static class Builder {
        private final ParameterMapping mapping = new ParameterMapping();
        
        public Builder(Configuration configuration, String property, Class<?> javaType) {
            mapping.configuration = configuration;
            mapping.property = property;
            mapping.javaType = javaType;
        }
        
        public Builder jdbcType(JdbcType jdbcType) {
            mapping.jdbcType = jdbcType;
            return this;
        }
        
        public ParameterMapping build() {
            resolveTypeHandler();
            return mapping;
        }
        
        private void resolveTypeHandler() {
            if (mapping.typeHandler == null && mapping.javaType != null) {
                TypeHandlerRegistry registry = mapping.configuration.getTypeHandlerRegistry();
                mapping.typeHandler = registry.getTypeHandler(mapping.javaType, mapping.jdbcType);
            }
        }
    }
    
    public String getProperty() {
        return property;
    }
    
    public TypeHandler<?> getTypeHandler() {
        return typeHandler;
    }
    
    public JdbcType getJdbcType() {
        return jdbcType;
    }
    
    public Class<?> getJavaType() {
        return javaType;
    }
}
